# -*- coding: utf-8 -*-

import json

from odoo import http
from odoo.http import request
from odoo import fields
from datetime import datetime

from .error_code import error_code
import logging

_logger = logging.getLogger(__name__)

class WxDealshopping(http.Controller):
    @http.route('/O2vvzbMkZv.txt',type='http',auth='public', methods=['GET'])
    def auth_fenxiao_rental(self):
        return '86d4dc8965d222a00e5e51f497996166'


    @http.route('/create/contact',type='http',auth='public', methods=['GET'])
    def createcontact(self, wxid=None,value=None,otherid=None, **kwargs):
        try:
            deal_value = json.loads(value)
            myself = request.env['res.partner'].sudo().search([
                    ('wechat_id', '=', int(wxid))
                ])
            return_otherid = 0
            if int(otherid) != 0:
                
                other_person = request.env['res.partner'].sudo().search([('id','=',int(otherid))])
                if len(other_person):
                    #判断是不是企业分销商
                    res = request.env['res.users'].sudo().search([('partner_id','=',int(otherid))])
                    if len(res):    #res.user的partner_id等于res.partner的id,就是企业分销商
                        if len(myself):
                            myself.write({
                                'name': deal_value['name'],
                                'phone': deal_value['phone'],
                                'street': deal_value['detail'], 
                                'fenxiao':int(otherid),
                                })
                            if myself.other_id:
                                return_otherid = myself.other_id.id
                        else:
                            myself = request.env['res.partner'].sudo().create({
                                'name': deal_value['name'],
                                'phone': deal_value['phone'],
                                'street': deal_value['detail'],
                                'wechat_id':int(wxid),
                                # 'other_id':int(otherid),
                                'fenxiao':int(otherid)
                            })
                            return_otherid = int(otherid)
                    else:
                        if len(myself):
                            myself.write({
                                'name': deal_value['name'],
                                'phone': deal_value['phone'],
                                'street': deal_value['detail'], 
                                'fenxiao':other_person.fenxiao.id,
                                })
                            if myself.other_id:
                                return_otherid = myself.other_id.id
                        else:
                            myself = request.env['res.partner'].sudo().create({
                                'name': deal_value['name'],
                                'phone': deal_value['phone'],
                                'street': deal_value['detail'],
                                'wechat_id':int(wxid),
                                'other_id':int(otherid),
                                'fenxiao':other_person.fenxiao.id
                            })
                            return_otherid = int(otherid)
                else:
                    if len(myself):
                        myself.write({
                            'name': deal_value['name'],
                            'phone': deal_value['phone'],
                            'street': deal_value['detail'], 
                            })
                        if myself.other_id:
                            return_otherid = myself.other_id.id
                    else:
                        myself = request.env['res.partner'].sudo().create({
                            'name': deal_value['name'],
                            'phone': deal_value['phone'],
                            'street': deal_value['detail'],
                            'wechat_id':int(wxid),
                            # 'other_id':int(otherid),
                            # 'fenxiao':other_person.fenxiao.id
                        })
            else:
                if len(myself):
                    myself.write({
                        'name': deal_value['name'],
                        'phone': deal_value['phone'],
                        'street': deal_value['detail'], 
                        })
                    if myself.other_id:
                        return_otherid = myself.other_id.id
                else:
                    myself = request.env['res.partner'].sudo().create({
                        'name': deal_value['name'],
                        'phone': deal_value['phone'],
                        'street': deal_value['detail'],
                        'wechat_id':int(wxid),
                        # 'other_id':int(otherid),
                        # 'fenxiao':other_person.fenxiao.id
                    })
                    


                      
            response = request.make_response(
                    headers={
                        "Content-Type": "json"
                    },
                    data=json.dumps({
                        'code':0,
                        'userid':myself.id,
                        'name': myself.name,
                        'otherid': return_otherid,
                    })
                )
            return response
        except AttributeError:
            return request.make_response(json.dumps({'code': 404, 'msg': error_code[404]}))

        except Exception as e:
            _logger.exception(e)
            return request.make_response(json.dumps({'code': -1, 'msg': error_code[-1], 'data': e.message}))


    @http.route('/submit/orderform',type='http',auth='public', methods=['GET'])
    def submitorder(self, userid=None, goodsid=None, goodsnum=None, **kwargs):
        try:
            _logger.info("kawayi")
            _logger.info(int(userid))
            _logger.info(int(goodsid))
            _logger.info(int(goodsnum))
            partner_id = int(userid)
            product_uom_qty = int(goodsnum)
            partnerid = request.env['res.partner'].sudo().search([
                    ('id', '=', partner_id)
                ])
            partnerid = partnerid[0]
            product = request.env['product.template'].sudo().search([('id', '=', int(goodsid))])
            product_product = request.env['product.product'].sudo().search([('product_tmpl_id', '=', int(goodsid))])
            product_id = product[0]
            # _logger.info(product_product.name)
            Param = request.env['ir.config_parameter']
            fen_level = Param.get_param('fen_level')
            fen_level = int(fen_level.encode("utf-8"))
            # _logger.info("hahahah")
            # _logger.info(fen_level)
            order = request.env['sale.order'].sudo().create({
                'partner_id': partnerid.id,
                'currency_id': partnerid.currency_id.id,
                'date_order': fields.Datetime.now(),
                'confirmation_date': fields.Datetime.now(),
                # 'name': str(datetime.today()),
                'partner_invoice_id': partnerid.id,
                'partner_shipping_id': partnerid.id,
                # 'state': 'draft', 
                'pricelist_id': request.env.ref('product.list0').id,
                'order_line': [(0, 0, {
                    # 'name': product_id.name,
                    # 'product_uom': product_id.uom_id.id,
                    'product_uom_qty': product_uom_qty,
                    # 'price_unit': order.amount_total,
                    # 'state': 'sale',
                    # 'customer_lead': 0.0,
                    'product_id': product_product.id,
                })],
            })
            _logger.info(order.name)
            if partnerid.fenxiao:
                # _logger.info(partnerid.fenxiao.name)
                order.sudo().write({'fen_company':partnerid.fenxiao.id})

            if fen_level > 0:
                if partnerid.other_id:
                    order.sudo().write({'third_sale':partnerid.other_id.id})
                if fen_level > 1:
                    if partnerid.other_id.other_id:
                        order.sudo().write({'second_sale':partnerid.other_id.other_id.id})
                        # if partnerid.other_id.fenxiao:
                        #     order.sudo().write({'fen_company':partnerid.other_id.fenxiao.id})
                    if fen_level > 2 :
                        if partnerid.other_id.other_id.other_id:
                            order.sudo().write({'first_sale':partnerid.other_id.other_id.other_id.id})
                            # if partnerid.other_id.other_id.fenxiao:
                            #     order.sudo().write({'fen_company':partnerid.other_id.other_id.fenxiao.id})
            if order.name:
                response = request.make_response(
                        headers={
                            "Content-Type": "json"
                        },
                        data=json.dumps({
                            'code':0,
                            'orderId':order.id,
                            'name': '卡哇伊',
                        })
                    )
            return response
        except AttributeError:
            return request.make_response(json.dumps({'code': 404, 'msg': error_code[404]}))

        except Exception as e:
            _logger.exception(e)
            return request.make_response(json.dumps({'code': -1, 'msg': error_code[-1], 'data': e.message}))


    @http.route('/change/orderform',type='http',auth='public', methods=['GET'])
    def changeorders(self,orderid=None, **kwargs):
        # _logger.info("gegegegegegegege")
        try:
            # _logger.info(int(orderid))
            order = request.env['sale.order'].sudo().search([('id','=',orderid)])
            order = order[0]
            order.state = 'sale'
            qty = 0
            for i in order.order_line:

                qty += i.product_uom_qty
                i.product_id.product_tmpl_id.product_no -= qty
                # _logger.info(i.product_id.product_tmpl_id.product_no)

            if order.fen_company:
                fen = request.env['res.partner'].sudo().search([('id','=',order.fen_company.id)])
                fen = fen[0]
                fen.stock_no -= qty
                request.env['fenxiao.stock'].sudo().create({
                    'user':fen.id,
                    'move_no':-qty,
                    'date':datetime.today()
                })

            _logger.info("1111111111111")
            product = order.order_line
            product = product[0]
            _logger.info(product)
            # product = product.product.product_tmpl_id
            # _logger.info("00000000000000")
            # _logger.info(product)
            # product = product[0]
            # product[0].product_no 

            Param = request.env()['ir.config_parameter']
            fen_level = Param.get_param('fen_level')
            fen_level = int(fen_level.encode("utf-8"))
            first = float(Param.get_param('first'))
            second = float(Param.get_param('second'))
            third = float(Param.get_param('third'))

            income = Param.get_param('income') or ''
            recipt = Param.get_param('recipt') or ''
            commission = Param.get_param('commission') or ''
            payable_1 = Param.get_param('payable_1') or ''
            payable_2 = Param.get_param('payable_2') or ''
            income = int(income.encode("utf-8"))
            recipt = int(recipt.encode("utf-8"))
            commission = int(commission.encode("utf-8"))
            payable_1 = int(payable_1.encode("utf-8"))
            payable_2 = int(payable_2.encode("utf-8"))
            _logger.info("ppppppppppp")
            journal = request.env['account.journal'].sudo().search([('name','=',u'客户发票')])
            journal = journal[0]
            move = request.env['account.move'].sudo().create({
                'journal_id': journal.id,
                'date': datetime.today(),
                'name': 'INV' + str(datetime.today()),
                'state': 'posted',
            })

            label='/'
            move.line_ids.sudo().create({
            'move_id': move.id,
            'account_id': recipt,      #微信账户
            'debit': order.amount_total,      #借方金额
            'credit': 0.0,
            'date_maturity': datetime.today(),
            'partner_id': order.partner_id.id,
            'name': label,
            })
            move.line_ids.create({
            'move_id': move.id,
            'account_id': income,   #主营业务收入
            'debit': 0.0,      
            'credit': order.amount_total,
            'date_maturity': datetime.today(),
            'partner_id': order.partner_id.id,
            'name': label,
            })
            if fen_level > 0:
                money = 0.0
                if order.third_sale:
                    money = order.amount_total * third/100
                    c = order.third_sale.commission
                    c += money
                    order.third_sale.commission = c
                    request.env['money.recond'].sudo().create({
                        'user': order.third_sale.id,
                        'sum': '+' + str(money),
                        'data': fields.Date.today()
                    })
                    move.line_ids.create({
                    'move_id': move.id,
                    'account_id': commission,
                    'debit': money,      #借方金额
                    'credit': 0.0,
                    'date_maturity': datetime.today(),
                    'partner_id': order.third_sale.id,
                    'name': label,
                    })
                    move.line_ids.create({
                    'move_id': move.id,
                    'account_id': payable_1,
                    'debit': 0.0,      
                    'credit': money,
                    'date_maturity': datetime.today(),
                    'partner_id': order.third_sale.id,
                    'name': label,
                    })
                order.third_sale_money = money
                if fen_level > 1:
                    money_1 = 0.0
                    if order.second_sale:
                        money_1 = order.amount_total * second/100
                        c = order.second_sale.commission
                        c += money_1
                        order.second_sale.commission = c
                        request.env['money.recond'].sudo().create({
                            'user': order.second_sale.id,
                            'sum': '+' + str(money_1),
                            'data': fields.Date.today()
                        })
                        move.line_ids.sudo().create({
                        'move_id': move.id,
                        'account_id': commission,
                        'debit': money_1,      #借方金额
                        'credit': 0.0,
                        'date_maturity': datetime.today(),
                        'partner_id': order.second_sale.id,
                        'name': label,
                        })
                        move.line_ids.sudo().create({
                        'move_id': move.id,
                        'account_id': payable_1,
                        'debit': 0.0,      
                        'credit': money_1,
                        'date_maturity': datetime.today(),
                        'partner_id': order.second_sale.id,
                        'name': label,
                        })
                    order.second_sale_money = money_1
                    if fen_level > 2:
                        money_2 = 0.0
                        if order.first_sale:
                            money_2 = order.amount_total * first/100
                            c = order.first_sale.commission
                            c += money_2
                            order.first_sale.commission = c
                            request.env['money.recond'].sudo().create({
                                'user': order.first_sale.id,
                                'sum': '+' + str(money_2),
                                'data': fields.Date.today()
                            })
                            move.line_ids.sudo().create({
                            'move_id': move.id,
                            'account_id': commission,
                            'debit': money_2,      #借方金额
                            'credit': 0.0,
                            'date_maturity': datetime.today(),
                            'partner_id': order.first_sale.id,
                            'name': label,
                            })
                            move.line_ids.sudo().create({
                            'move_id': move.id,
                            'account_id': payable_1,
                            'debit': 0.0,      
                            'credit': money_2,
                            'date_maturity': datetime.today(),
                            'partner_id': order.first_sale.id,
                            'name': label,
                            })
                        order.first_sale_money = money_2

        except AttributeError:
            return request.make_response(json.dumps({'code': 404, 'msg': error_code[404]}))

        except Exception as e:
            _logger.exception(e)
            return request.make_response(json.dumps({'code': -1, 'msg': error_code[-1], 'data': e.message}))



    @http.route('/obtain/ordersform',type='http',auth='public', methods=['GET'])
    def changeorder(self, userid=None, state=None, **kwargs):
        try:
            _logger.info(userid)
            _logger.info(state)
            _logger.info("qqqqqqqqqqqqqqqqqqq")
            result = []
            
            if state == '8':
                orders = request.env['sale.order'].sudo().search([
                    ('partner_id', '=', int(userid))])
            else:
                orders = request.env['sale.order'].sudo().search([
                    ('partner_id', '=', int(userid)),
                    ('statement','=',state)]) 
            for order in orders:
                res = {}
                res['id'] = order.id
                res['name'] = order.name
                # _logger.info(res['name'])
                res['user'] = order.partner_id.name
                res['time'] = order.date_order
                res['state'] = order.statement
                res['product'] = []
                for pro_list in order.order_line:
                    rec = {}
                    rec['product'] = pro_list.product_id.name
                    rec['num'] = pro_list.product_uom_qty
                    res['product'].append(rec)
                result.append(res)
            _logger.info(result)
            response = request.make_response(
                        headers={
                            "Content-Type": "json"
                        },
                        data=json.dumps({
                            'code':0,
                            'result':result,
                            'name': '卡哇伊',
                        })
                    )
            return response
                    


        except AttributeError:
            return request.make_response(json.dumps({'code': 404, 'msg': error_code[404]}))

        except Exception as e:
            _logger.exception(e)
            return request.make_response(json.dumps({'code': -1, 'msg': error_code[-1], 'data': e.message}))
